#pragma once
#include <iostream>
#include <arpa/inet.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <memory>
#include <functional>
#include "inetAddr.hpp"
#include "log.hpp"
#include "common.hpp"
#include "Socket.hpp"

using namespace LogModule;

using ioserver_t = std::function<void(std::shared_ptr<Socket> &sock, InetAddr &addr)>;

const static int backlog = 8;

class TcpServer : public Nocopy
{
public:
    TcpServer(const InetAddr &addr, ioserver_t service)
        : _socket(std::make_unique<UdpSocket>()), _addr(addr), _isRuning(false), _service(service)
    {
        _socket->BuiltUdpServerSocket(_addr);
    }

    void Start()
    {
        _isRuning = true;
        while (_isRuning)
        {
            InetAddr client;
            std::shared_ptr<Socket> sock = _socket->AcceptOper(client);
            if (sock == nullptr)
            {
                continue;
            }
            //LOG((int)LogLevel::DEBUG) << "accept success ...";
            //通过让孤儿进程去执行service方法
            pid_t id = fork();
            if(id < 0)
            {
                LOG((int)LogLevel::FATAL) << "fork error ...";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                // 子进程 -> listensock
                LOG((int)LogLevel::INFO) << "远端机器 : " << client.AddrMessage() << "已连接！";
                _socket->Close();
                if(fork() > 0)
                    exit(OK);
                // 孙子进程在执行任务，已经是孤儿了
                _service(sock, client);
                exit(OK);
            }
            else
            {
                // 父进程 -> sock
                sock->Close();
                pid_t rid = ::waitpid(id, nullptr, 0);
                (void)rid;
            }
        }
    }

    ~TcpServer()
    {
    }

private:
    std::unique_ptr<Socket> _socket;
    InetAddr _addr;
    bool _isRuning;
    ioserver_t _service;
};